package com.study.jdbc.junit;

import java.sql.Connection;

import com.study.jdbc.utils.DBCPUtil;

/**
* @Name: TransactionManager
* @Description: 事务管理工具类
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-19 下午9:39:51 
* @Version: V1.0
 */
public class TransactionManager {
	
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>() ;
	
	public static Connection getConnection() {
		Connection conn = tl.get() ; //从当前线程中获取数据库连接
		if(conn == null) {
			conn = DBCPUtil.getConnection() ;
			tl.set(conn) ; //将获取到的连接设置到当前线程中
		}
		return conn ;
	}
	
	public static void startTransaction() {
		Connection conn = getConnection() ;
		try {
			conn.setAutoCommit(false) ;
		} catch (Exception e) {
			e.printStackTrace() ;
		}
	}
	
	public static void commit() {
		Connection conn = getConnection() ;
		try {
			conn.commit() ;
		} catch (Exception e) {
			e.printStackTrace() ;
		}
	}
	
	public static void rollback() {
		Connection conn = getConnection() ;
		try {
			conn.rollback() ;
		} catch (Exception e) {
			e.printStackTrace() ;
		}
	}
	
	public static void close() {
		Connection conn = getConnection() ;
		try {
			conn.close() ;
			tl.remove() ; //从当前线程中解绑数据库连接
		} catch (Exception e) {
			e.printStackTrace() ;
		}
	}

}

